package com.example.common.network;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import com.example.common.utils.LogUtil;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class HeaderManager {
    
    private static volatile HeaderManager instance;
    private Map<String, String> commonHeaders;
    private Map<String, String> dynamicHeaders;
    private Context context;
    
    private HeaderManager(Context context) {
        this.context = context.getApplicationContext();
        this.commonHeaders = new HashMap<>();
        this.dynamicHeaders = new HashMap<>();
        initCommonHeaders();
    }
    
    public static void init(Context context) {
        if (instance == null) {
            synchronized (HeaderManager.class) {
                if (instance == null) {
                    instance = new HeaderManager(context);
                }
            }
        }
    }
    
    public static HeaderManager getInstance() {
        if (instance == null) {
            throw new IllegalStateException("HeaderManager must be initialized first");
        }
        return instance;
    }
    
    /**
     * 初始化通用Header
     */
    private void initCommonHeaders() {
        // 基础Headers
        commonHeaders.put(NetworkConfig.HEADER_CONTENT_TYPE, NetworkConfig.CONTENT_TYPE_JSON);
        commonHeaders.put(NetworkConfig.HEADER_ACCEPT, NetworkConfig.CONTENT_TYPE_JSON);
        
        // 设备信息
        commonHeaders.put(NetworkConfig.HEADER_USER_AGENT, getUserAgent());
        commonHeaders.put(NetworkConfig.HEADER_DEVICE_ID, getDeviceId());
        
        // 应用版本
        try {
            PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            commonHeaders.put(NetworkConfig.HEADER_APP_VERSION, packageInfo.versionName);
        } catch (PackageManager.NameNotFoundException e) {
            LogUtil.e("HeaderManager", "Failed to get app version", e);
        }
        
        LogUtil.d("HeaderManager", "Common headers initialized");
    }
    
    /**
     * 获取User-Agent
     */
    private String getUserAgent() {
        return String.format("%s/%s (Android %s; %s %s)",
                context.getPackageName(),
                getAppVersion(),
                Build.VERSION.RELEASE,
                Build.MANUFACTURER,
                Build.MODEL);
    }
    
    /**
     * 获取应用版本
     */
    private String getAppVersion() {
        try {
            PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            return packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            return "1.0.0";
        }
    }
    
    /**
     * 获取设备ID（这里使用随机UUID，实际项目中可能需要其他方案）
     */
    private String getDeviceId() {
        // 在实际项目中，可能需要使用ANDROID_ID或其他唯一标识
        // 这里为了演示使用UUID
        return UUID.randomUUID().toString();
    }
    
    /**
     * 添加动态Header
     */
    public void addDynamicHeader(String key, String value) {
        dynamicHeaders.put(key, value);
        LogUtil.d("HeaderManager", "Added dynamic header: " + key);
    }
    
    /**
     * 移除动态Header
     */
    public void removeDynamicHeader(String key) {
        dynamicHeaders.remove(key);
        LogUtil.d("HeaderManager", "Removed dynamic header: " + key);
    }
    
    /**
     * 清除所有动态Header
     */
    public void clearDynamicHeaders() {
        dynamicHeaders.clear();
        LogUtil.d("HeaderManager", "Cleared all dynamic headers");
    }
    
    /**
     * 获取所有Header（通用 + 动态）
     */
    public Map<String, String> getAllHeaders() {
        Map<String, String> allHeaders = new HashMap<>(commonHeaders);
        allHeaders.putAll(dynamicHeaders);
        
        // 添加Token Header
        String authHeader = getAuthorizationHeader();
        if (authHeader != null) {
            allHeaders.put(NetworkConfig.HEADER_AUTHORIZATION, authHeader);
        }
        
        return allHeaders;
    }
    
    /**
     * 获取通用Header
     */
    public Map<String, String> getCommonHeaders() {
        return new HashMap<>(commonHeaders);
    }
    
    /**
     * 获取动态Header
     */
    public Map<String, String> getDynamicHeaders() {
        return new HashMap<>(dynamicHeaders);
    }
    
    /**
     * 获取Authorization Header
     */
    private String getAuthorizationHeader() {
        try {
            TokenManager tokenManager = TokenManager.getInstance();
            if (tokenManager.hasValidToken()) {
                return tokenManager.getAuthorizationHeader();
            }
        } catch (IllegalStateException e) {
            LogUtil.w("HeaderManager", "TokenManager not initialized");
        }
        return null;
    }
    
    /**
     * 设置Content-Type
     */
    public void setContentType(String contentType) {
        commonHeaders.put(NetworkConfig.HEADER_CONTENT_TYPE, contentType);
    }
    
    /**
     * 重置Content-Type为JSON
     */
    public void resetContentTypeToJson() {
        setContentType(NetworkConfig.CONTENT_TYPE_JSON);
    }
    
    /**
     * 设置Accept
     */
    public void setAccept(String accept) {
        commonHeaders.put(NetworkConfig.HEADER_ACCEPT, accept);
    }
}